"""This module provides mydouyn"""

import json
import logging
import os
import platform
import time

from playwright.sync_api import Page, sync_playwright


# from pythonTryEverything.putdonwphone.data import englisword
# from putdonwphone.data import englisword
class CMyRedBook:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """

    def __init__(
        self,
        cookies_path: str,
        login_url: str,
        upload_picture_url: str,
        upload_mp4_url: str,
    ):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_picture_url = upload_picture_url
        self.upload_mp4_url = upload_mp4_url
        # playwright 部分
        self.browser = None
        self.page = None
        print("create CMyRedBook")

    def __del__(self):
        print("CMyRedBook is being destroyed")

    def upload_picture(self, picture_path: str, habit_name: str, habit_detail: str):
        """
        upload_picture
        """
        with sync_playwright() as playwright:
            display_headless = False
            # display_headless = True
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
            if sys == "Linux":
                self.browser = playwright.chromium.launch(headless=display_headless)
            else:
                self.browser = playwright.chromium.launch(
                    channel="chrome", headless=display_headless
                )
            login_page = self.login_or_restore_cookies()
            self.msg_up_load(login_page, picture_path, habit_name, habit_detail)
            self.browser.close()

    def login_or_restore_cookies(self) -> Page:
        """
        登录
        """
        user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.21 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"

        context = self.browser.new_context(user_agent=user_agent)
        context.clear_cookies()
        page = context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            print("load cookies--------------------")
            # 从文件中加载 cookies
            with open(self.cookies_path, "r", encoding="utf-8") as f:
                cookies = json.load(f)
            context.add_cookies(cookies)
            time.sleep(3)
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            print("扫名二维码登录 需要人工处理--------------------")
            time.sleep(60)
            cookies = page.context.cookies()
            with open(self.cookies_path, "w", encoding="utf-8") as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page

    def msg_up_load(
        self, page: Page, picture_path: str, habit_name: str, habit_detail: str
    ):
        """
        上传图文
        """
        page.goto(self.upload_picture_url)
        time.sleep(3)
        print(f"open  {self.upload_picture_url}")
        # 使用文本内容定位元素
        example_element = page.locator("xpath=//span[contains(text(), '上传图文')]")
        example_element.click()
        print("点击 发布图文")
        time.sleep(4)

        # # page.locator('.drag-over').locator('nth=0').click()
        # page.locator('.drag-over').locator('nth=0').set_input_files()
        # # page.locator(
        # #     ":has-text(\"最多支持上传18张\")").locator('nth=1').set_input_files(
        # #     picture_path)

        # 点击选择文件，输入文件
        with page.expect_file_chooser() as fc_info:
            # 找到拖拽区域
            page.locator(".drag-over").locator("nth=0").click()
            # 问题 文件弹框后 不自动退出 无法后续自动化操作
            file_chooser = fc_info.value
            file_chooser.set_files(picture_path)

        time.sleep(4)
        print("上传图片")
        # 填写标题，可能会有更多赞哦～
        page.locator("css=.c-input_inner").fill(habit_name)
        time.sleep(3)
        # 填写更全面的描述信息，让更多的人看到你吧！
        page.locator("css=.post-content").fill(habit_detail)
        time.sleep(3)
        page.mouse.down()
        page.mouse.down()
        time.sleep(1)
        # 发布
        page.locator("xpath=//button[./span[text()='发布']]").click()
        print("发布")
        time.sleep(8)

    def tell_good(self, habit_name: str, habit_detail: str):
        """
        upload_picture
        """
        with sync_playwright() as playwright:
            self.browser = playwright.chromium.launch(headless=False)
            login_page = self.login_or_restore_cookies()
            self.tell_good_nowcoder(login_page, habit_name, habit_detail)
            self.browser.close()

    def tell_good_nowcoder(self, page: Page, habit_name: str, habit_detail: str):
        """
        发布笔记
        """
        page.goto(self.upload_picture_url)
        page.wait_for_timeout(1 * 1000)
        print(f"open  {self.upload_picture_url}")

        # 控制发文的次数
        begin = 4
        end = 12
        step = 1
        # 点击点赞100次
        for i in range(begin, end):
            for j in range(0, 5):
                page.mouse.down()
                page.mouse.down()
                page.wait_for_timeout(100)
            page.wait_for_timeout(step * 1000)
            print(f"click {i}")

            # open
            with page.expect_popup() as jump_page_info:
                page.locator(
                    f"div:nth-child({i}) > div:nth-child(4) > div:nth-child(2) > .sc-CtfFt > .sc-laTMn"
                ).click()
            msg_page = jump_page_info.value
            msg_page.wait_for_timeout(1 * 1000)
            msg_page.locator(".inputPanel").click()
            msg_page.wait_for_timeout(1 * 1000)
            msg_page.locator(".inputPanel").fill(habit_detail)
            msg_page.wait_for_timeout(1 * 1000)
            msg_page.get_by_text("发布", exact=True).click()
            msg_page.wait_for_timeout(1 * 1000)
            msg_page.close()
            msg_page.wait_for_timeout(1 * 1000)

            print(f"agree{i}")

            # page.locator(
            #     f"div:nth-child({i}) > .tw-px-5 > div:nth-child(4) > span:nth-child(2) > .feed-interaction-data > .ncicon > svg"
            # ).click()
            # page.wait_for_timeout(2000)
            # print(f"msg-comment-open-{i}")
            # page.mouse.down()
            # page.mouse.down()
            # time.sleep(1)
            # write comment
            # 等待元素可见
            # page.wait_for_selector(
            #     'div[id*="nc-e-textarea"]', state="visible", timeout=10000
            # )

            # # 找到所有匹配元素
            # textareas = page.locator('div[id*="nc-e-textarea"]')
            # count = textareas.count()

            # 调试输出
            # print(f"找到 {count} 个文本输入区域")
            # time.time(60)
            # print(f"msg-comment-done-{i}")
            # # commit
            # page.get_by_role("button", name="评论").first.click()
            # page.wait_for_timeout(2000)
            # print(f"msg-comment-finish-{i}")
            # page.locator(".close").click()
            # page.wait_for_timeout(2000)
            # print(f"msg-comment-close-{i}")

    #################################################################################

    def crate_browser_instance(self):
        """
        crate_browser_instance
        https://playwright.dev/python/docs/library
        playwright = sync_playwright().start()
        """
        display_headless = False
        playwright = sync_playwright().start()
        if platform.system() == "Linux":
            display_headless = True
            self.browser = playwright.chromium.launch(headless=display_headless)
        else:
            self.browser = playwright.chromium.launch(
                channel="chrome", headless=display_headless
            )

        self.page = self.login_or_restore_cookies()
        # self.msg_up_load(login_page, picture_path, habit_name, habit_detail)


####################################
def interface_auo_tell_good_maimai(artile_title, artile_content):
    """
    对外调用接口
    """
    sys = platform.system()
    login_url = "https://maimai.cn/"
    upload_picture_url = "https://maimai.cn/gossip_list"
    upload_mp4_url = "https://maimai.cn/gossip_list"
    sys = platform.system()
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\maimai_small.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/maimai_small.json"
    else:
        cookies_path = r"/root/bin/nowcoder_small.json"

    autoupload = CMyRedBook(cookies_path, login_url, upload_picture_url, upload_mp4_url)

    try:
        autoupload.tell_good(artile_title, artile_content)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
    finally:
        print("...")


if __name__ == "__main__":
    # 获取内容
    local_file_path = (
        r"/Users/wangchuanyi/money/years/p1_good_night/auto/good/nowcoder/config.txt"
    )
    f = open(local_file_path, encoding="utf-8")
    artile_content = f.read()
    print(artile_content)
    f.close()

    artile_title = "学会销售自己的产品"

    interface_auo_tell_good_maimai(artile_title, artile_content)

## playwright codegen https://maimai.cn/gossip_list
